<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" class="search-form">
                <el-row :gutter="20">
                    <el-col :span="3">
                        <el-form-item label="报表类型">
                            <el-select v-model="searchForm.reportType" placeholder="请选择报表类型"
                                @change="handleReportTypeChange" style="width: 100%">
                                <el-option label="水质指标报表" value="indicator" />
                                <el-option label="水质监测报表" value="monitor" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="3">
                        <el-form-item label="监测站点">
                            <el-select v-model="searchForm.stationId" placeholder="请选择站点" clearable
                                @change="handleSiteChange" style="width: 100%">
                                <el-option v-for="item in siteOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="3" v-if="searchForm.reportType === 'indicator'">
                        <el-form-item label="水质指标">
                            <el-select v-model="searchForm.indicatorCode" placeholder="请选择指标" clearable
                                style="width: 100%">
                                <el-option v-for="item in monitoringOptions" :key="item.siteAdminId" :label="item.monitorName"
                                :value="item.monitorCode" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="3" v-if="searchForm.reportType === 'monitor'">
                        <el-form-item label="监测任务">
                            <el-select v-model="searchForm.taskId" placeholder="请选择任务" clearable style="width: 100%">
                                <el-option v-for="item in taskOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="3">
                        <el-form-item label="数据状态">
                            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%">
                                <el-option label="全部" :value="null" />
                                <el-option label="达标" :value="1" />
                                <el-option label="不达标" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="时间范围">
                            <el-date-picker v-model="searchForm.timeRange" type="datetimerange" range-separator="至"
                                start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                                :shortcuts="timeShortcuts" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <div class="form-actions">
                            <el-button type="primary" @click="handleSearch" :loading="loading">
                                <el-icon class="el-icon--left">
                                    <Search />
                                </el-icon>
                                查询
                            </el-button>
                            <el-button @click="resetSearch">
                                <el-icon class="el-icon--left">
                                    <Refresh />
                                </el-icon>
                                重置
                            </el-button>
                            <el-button type="success" @click="handleExport" :disabled="tableData.length === 0">
                                <el-icon class="el-icon--left">
                                    <Download />
                                </el-icon>
                                导出Excel
                            </el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <!-- 数据展示区域 -->
        <div class="data-container">
            <el-card>
                <el-table :data="tableData" border stripe style="width: 100%" :max-height="600">
                    <el-table-column v-for="column in tableColumns" :key="column.field" :prop="column.field"
                        :label="column.title" :align="getColumnAlign(column.field)"
                        :min-width="getColumnWidth(column.field)" show-overflow-tooltip>
                        <template #default="{ row }">
                            <span :class="getCellClass(row, column.field)">
                                {{ formatCellValue(row[column.field], column.field) }}
                            </span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import Echarts from '@/components/ECharts'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()

// API引入
import {
    getSiteList,
    getMonitoringListBySite,
    getIndicatorReport,
    getMonitorReport
} from '@/api/dispatch/analyze/water_quality_analysis'


// 搜索表单
const searchForm = reactive({
    reportType: 'indicator',
    stationId: '',
    indicatorCode: '',
    taskId: '',
    status: null,
    timeRange: [
        dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
        dayjs().format('YYYY-MM-DD HH:mm:ss')
    ]
})

// 下拉选项
const siteOptions = ref([])
const monitoringOptions = ref([])
const taskOptions = ref([
    { id: 1, name: '日常监测任务' },
    { id: 2, name: '专项监测任务' },
    { id: 3, name: '应急监测任务' }
])

// 报表数据
const reportData = reactive({
    title: '',
    queryTime: '',
    columns: [],
    rows: []
})

// 表格数据
const tableData = computed(() => reportData.rows || [])
const tableColumns = computed(() => reportData.columns || [])
const loading = ref(false)

// 图表状态
const showChart = ref(true)
const chartType = ref('line')

// 初始化数据
onMounted(() => {
    initData()
})

// 初始化数据
const initData = async () => {
    try {
        await fetchSiteList()

        // 设置默认站点
        if (siteOptions.value.length > 0) {
            searchForm.stationId = siteOptions.value[0].id
        }

        // 查询数据
        await fetchReportData()
    } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('初始化数据失败')
    }
}

// 获取站点列表
const fetchSiteList = async () => {
    try {
        const res = await getSiteList()
        siteOptions.value = res.data || []

        const result = await getMonitoringListBySite({ siteId: siteOptions.value[0].id });
        monitoringOptions.value = result.data;
        console.log(result);
        
    } catch (error) {
        console.error('获取站点列表失败:', error)
        ElMessage.error('获取站点列表失败')
    }
}

// 获取报表数据
const fetchReportData = async () => {
    try {
        loading.value = true

        const params = {
            beginTime: searchForm.timeRange?.[0] || '',
            endTime: searchForm.timeRange?.[1] || '',
            stationId: searchForm.stationId || '',
            status: searchForm.status
        }

        // 根据报表类型添加特定参数
        if (searchForm.reportType === 'indicator') {
            params.indicatorCode = searchForm.indicatorCode || ''
        } else if (searchForm.reportType === 'monitor') {
            params.taskId = searchForm.taskId || ''
        }

        let res
        if (searchForm.reportType === 'indicator') {
            res = await getIndicatorReport(params)
        } else {
            res = await getMonitorReport(params)
        }

        Object.assign(reportData, res.data || {})

        if (tableData.value.length === 0) {
            ElMessage.warning('该时间段内暂无数据')
        } else {
            ElMessage.success(`查询成功，共 ${tableData.value.length} 条记录`)
        }
    } catch (error) {
        console.error('查询报表数据失败:', error)
        ElMessage.error('查询报表数据失败')
    } finally {
        loading.value = false
    }
}

// 处理报表类型变化
const handleReportTypeChange = (type) => {
    // 重置相关参数
    if (type === 'indicator') {
        searchForm.taskId = ''
    } else {
        searchForm.indicatorCode = ''
    }
    fetchReportData()
}

// 处理站点变化
const handleSiteChange = (siteId) => {
    if (siteId) {
        fetchReportData()
    }
}

// 处理查询
const handleSearch = () => {
    fetchReportData()
}

// 重置搜索
const resetSearch = () => {
    Object.assign(searchForm, {
        reportType: 'indicator',
        stationId: siteOptions.value.length > 0 ? siteOptions.value[0].id : '',
        indicatorCode: '',
        taskId: '',
        status: null,
        timeRange: [
            dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
            dayjs().format('YYYY-MM-DD HH:mm:ss')
        ]
    })
    handleSearch()
}

// 导出Excel
const handleExport = async () => {
    try {
        if (tableData.value.length === 0) {
            ElMessage.warning('没有数据可导出')
            return
        }

        const params = {
            beginTime: searchForm.timeRange?.[0] || '',
            endTime: searchForm.timeRange?.[1] || '',
            stationId: searchForm.stationId || '',
            status: searchForm.status
        }

        // 根据报表类型添加特定参数
        if (searchForm.reportType === 'indicator') {
            params.indicatorCode = searchForm.indicatorCode || ''
        } else if (searchForm.reportType === 'monitor') {
            params.taskId = searchForm.taskId || ''
        }

        let exportUrl, fileName
        if (searchForm.reportType === 'indicator') {
            exportUrl = '/dispatch/system/waterQualityReport/indicator/export'
            fileName = `水质指标报表_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
        } else {
            exportUrl = '/dispatch/system/waterQualityReport/monitor/export'
            fileName = `水质监测报表_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
        }

        // 使用proxy.download进行导出
        proxy.download(exportUrl, params, fileName)
        ElMessage.success('导出任务已开始')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 刷新数据
const refreshData = () => {
    fetchReportData()
}

// 切换图表显示
const toggleChart = () => {
    showChart.value = !showChart.value
}

// 计算属性
const reportTitle = computed(() => {
    return searchForm.reportType === 'indicator' ? '水质指标报表' : '水质监测报表'
})

// 工具函数
const getColumnAlign = (field) => {
    if (field.includes('time') || field.includes('date')) {
        return 'center'
    }
    if (field.includes('value') || field.includes('val') || field.includes('数量') || field.includes('浓度')) {
        return 'right'
    }
    return 'left'
}

const getColumnWidth = (field) => {
    const column = tableColumns.value.find(col => col.field === field)
    const titleLength = column?.title?.length || 0
    return Math.max(120, titleLength * 12 + 20)
}

const getCellClass = (row, field) => {
    const value = row[field]

    if (typeof value === 'number') {
        // 根据业务规则设置样式
        if (field.includes('status') || field.includes('达标')) {
            return value === 1 ? 'cell-normal' : 'cell-abnormal'
        }

        // 数值范围判断
        if (field.includes('ph')) {
            if (value >= 6.5 && value <= 8.5) return 'cell-normal'
            return 'cell-abnormal'
        }

        if (field.includes('浊度') || field.includes('turbidity')) {
            if (value <= 1) return 'cell-normal'
            return 'cell-abnormal'
        }
    }

    return ''
}

const formatCellValue = (value, field) => {
    if (value == null || value === '') return '-'

    if (typeof value === 'number') {
        // 状态字段
        if (field.includes('status') || field.includes('达标')) {
            return value === 1 ? '达标' : '不达标'
        }

        // 数值字段
        if (field.includes('ph')) {
            return value.toFixed(2)
        }
        if (field.includes('浓度') || field.includes('含量') || field.includes('value')) {
            return value.toFixed(3)
        }
        return value.toFixed(2)
    }

    // 时间字段格式化
    if (field.includes('time') || field.includes('date')) {
        try {
            return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
        } catch {
            return value
        }
    }

    return value
}
</script>

<style scoped lang="scss">
.app-container {
    padding: 20px;
}

.form-actions {
    text-align: center;
}

.report-info {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.info-item {
    display: flex;
    align-items: center;
}

.info-label {
    color: #666;
    font-weight: bold;
    margin-right: 8px;
}

.info-value {
    color: #409eff;
    font-weight: bold;
}

.data-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.chart-card {
    margin-bottom: 20px;
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chart-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

.table-card {
    margin-bottom: 20px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

.empty-table {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
}

/* 单元格样式 */
.cell-normal {
    color: #67c23a;
    font-weight: bold;
}

.cell-abnormal {
    color: #f56c6c;
    font-weight: bold;
}

:deep(.el-table) {
    .cell {
        white-space: nowrap;
    }
}

:deep(.el-card) {
    margin-bottom: 20px;
}

:deep(.el-card):last-child {
    margin-bottom: 0;
}
</style>